﻿namespace X2OPC.Core.Common
{
    using System;
    using System.Runtime.InteropServices;
    using System.Runtime.CompilerServices;

    public class EnumUnknown : IEnumUnknown
    {
        /// <summary>
        ///  原数据
        /// </summary>
        private object[] _sources;
        /// <summary>
        ///  当前下标
        /// </summary>
        private int current;
        /// <summary>
        ///  大小
        /// </summary>
        private int size;
        /// <summary>
        ///  构造函数
        /// </summary>
        /// <param name="sources"></param>
        public EnumUnknown(object[] sources)
        {
            _sources = sources;
            this.current = 0;
            this.size = (sources == null) ? 0 : _sources.Length;
        }
        #region IEnumUnknown 成员

        /// <summary>
        ///  跳转到某个
        /// </summary>
        /// <param name="index">所需要跳转的数量</param>        
        /// <returns>是否成功</returns>
        [PreserveSig]
        public int Skip([In, MarshalAs(UnmanagedType.U4)] int celt)
        {
            this.current += celt;
            if (this.current >= this.size)
            {
                return 1;
            }
            return 0;
        }
        /// <summary>
        ///  重置
        /// </summary>
        public void Reset()
        {
            this.current = 0;
        }
        /// <summary>
        ///  复制
        /// </summary>
        /// <param name="enumerator">对象</param>
        public void Clone(out IEnumUnknown enumerator)
        {
            enumerator = new EnumUnknown(this._sources);
        }

        public int Next(int elementArrayLength, object[] elementArray, out int fetchedElementCount)
        {
            fetchedElementCount = 0;
            if (elementArrayLength < 0)
            {
                return -2147024809;
            }

            int index = 0;

            while ((this.current < this.size) && (elementArrayLength > 0))
            {
                object item = this._sources[this.current];
                bool useDisplayMember = false;

                if (!useDisplayMember)
                {
                    if (item != null)
                        elementArray[index] = item;
                }
                current++;
                index++;
                elementArrayLength--;
            }

            fetchedElementCount = index;
            if (elementArrayLength != 0)
            {
                return 1;
            }

            return 0;
        }

        #endregion
    }
}